package com.xyht.sca_s.student_manage_system.modules.dormitory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.SmsDormitory;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.SmsDormitoryBuilding;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.SmsDormitoryFloor;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.req.SmsDormitoryFloorAddReq;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.req.SmsDormitoryFloorDeletedReq;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.req.SmsDormitoryFloorUpdateReq;
import com.xyht.sca_s.student_manage_system.modules.dormitory.entity.resp.SmsDormitoryFloorResp;
import com.xyht.sca_s.student_manage_system.modules.dormitory.mapper.SmsDormitoryBuildingMapper;
import com.xyht.sca_s.student_manage_system.modules.dormitory.mapper.SmsDormitoryFloorMapper;
import com.xyht.sca_s.student_manage_system.modules.dormitory.mapper.SmsDormitoryMapper;
import com.xyht.sca_s.student_manage_system.modules.dormitory.service.SmsDormitoryFloorService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.dormitory.constant.RuleFlagConstant.FLAG_NORMAL;
import static com.xyht.sca_s.student_manage_system.modules.dormitory.constant.RuleFlagConstant.FLAG_RULE;

/**
 * <p>
 * 宿舍楼层管理表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2024-01-08
 */
@Service
public class SmsDormitoryFloorServiceImpl extends ServiceImpl<SmsDormitoryFloorMapper, SmsDormitoryFloor> implements SmsDormitoryFloorService {

    @Resource
    private SmsDormitoryFloorMapper dormitoryFloorMapper;
    @Resource
    private SmsDormitoryBuildingMapper dormitoryBuildingMapper;
    @Resource
    private SmsDormitoryMapper dormitoryMapper;

    @Override
    public ResponseResult addDormitoryFloor(String userId, SmsDormitoryFloorAddReq addReq) {
        if (isNullOrEmpty(addReq.getBuildingId(),addReq.getRuleFlag())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        //校验楼栋
        SmsDormitoryBuilding smsDormitoryBuilding = dormitoryBuildingMapper.selectById(addReq.getBuildingId());
        if (isNullOrEmpty(smsDormitoryBuilding)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_BUILDING_NOT_EXIST);
        }

        Integer ruleFlag = addReq.getRuleFlag();
        //1.普通规则
        if (ruleFlag == FLAG_NORMAL) {
            if (isNullOrEmpty(addReq.getFloorName())) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
            List<SmsDormitoryFloor> dormitoryFloorList = dormitoryFloorMapper.selectList(new LambdaQueryWrapper<SmsDormitoryFloor>()
                    .eq(SmsDormitoryFloor::getBuildingId, addReq.getBuildingId())
                    .eq(SmsDormitoryFloor::getFloorName,addReq.getFloorName()));
            if (!dormitoryFloorList.isEmpty()) {
                return CommonResult.failed(CommonCodeEnum.DORMITORY_NAME_EXIST);
            }
            SmsDormitoryFloor smsDormitoryFloor = new SmsDormitoryFloor();
            smsDormitoryFloor.setFloorName(addReq.getFloorName());
            smsDormitoryFloor.setBuildingId(addReq.getBuildingId());
            smsDormitoryFloor.setUserId(userId);
            dormitoryFloorMapper.insert(smsDormitoryFloor);
        //2.规则
        }else if(ruleFlag == FLAG_RULE) {
            if (isNullOrEmpty(addReq.getFloorNumber())) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
            //校验楼层数
            Integer floorNumber = addReq.getFloorNumber();
            if (floorNumber < 1) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }

            List<SmsDormitoryFloor> dormitoryFloorList = dormitoryFloorMapper.selectList(new LambdaQueryWrapper<SmsDormitoryFloor>()
                    .eq(SmsDormitoryFloor::getBuildingId, addReq.getBuildingId()));
            //2.1楼栋已设有楼层
            if (!dormitoryFloorList.isEmpty()) {
                List<Integer> floorNameList = dormitoryFloorList.stream().map(SmsDormitoryFloor::getFloorName)
                        .sorted().collect(Collectors.toList());
                //中间楼层被删除 依次填充并添加
                for (int i = 1; i <= floorNumber; i++) {
                    int j = 1;
                    while (floorNameList.contains(j)) {
                        j++;
                    }
                    SmsDormitoryFloor smsDormitoryFloor = new SmsDormitoryFloor();
                    smsDormitoryFloor.setFloorName(j);
                    smsDormitoryFloor.setBuildingId(addReq.getBuildingId());
                    smsDormitoryFloor.setUserId(userId);
                    dormitoryFloorMapper.insert(smsDormitoryFloor);
                    floorNameList.add(j);

                }
            //2.2楼栋没有设楼层
            }else {
                for (int i = 1; i <= floorNumber; i++) {
                    SmsDormitoryFloor smsDormitoryFloor = new SmsDormitoryFloor();
                    smsDormitoryFloor.setFloorName(i);
                    smsDormitoryFloor.setBuildingId(addReq.getBuildingId());
                    smsDormitoryFloor.setUserId(userId);
                    dormitoryFloorMapper.insert(smsDormitoryFloor);
                }
            }
        }else {
            return CommonResult.failed(CommonCodeEnum.FAIL);
        }

        return CommonResult.success();
    }

    @Override
    public ResponseResult deletedDormitoryFloor(SmsDormitoryFloorDeletedReq deletedReq) {
        if (isNullOrEmpty(deletedReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsDormitoryFloor smsDormitoryFloor = dormitoryFloorMapper.selectById(deletedReq.getId());
        if (isNullOrEmpty(smsDormitoryFloor)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_FLOOR_NOT_EXIST);
        }
        //删除房间
        dormitoryMapper.delete(new LambdaQueryWrapper<SmsDormitory>().eq(SmsDormitory::getFloorId,deletedReq.getId()));
        //删除楼层
        dormitoryFloorMapper.deleteById(deletedReq.getId());
        return CommonResult.success();
    }

    @Override
    public ResponseResult updateDormitoryFloor(SmsDormitoryFloorUpdateReq updateReq) {
        if (isNullOrEmpty(updateReq.getId(),updateReq.getFloorName())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsDormitoryFloor smsDormitoryFloor = dormitoryFloorMapper.selectById(updateReq.getId());
        if (isNullOrEmpty(smsDormitoryFloor)) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_FLOOR_NOT_EXIST);
        }

        //校验名是否重复
        List<SmsDormitoryFloor> dormitoryFloorList = dormitoryFloorMapper.selectList(new LambdaQueryWrapper<SmsDormitoryFloor>()
                .eq(SmsDormitoryFloor::getFloorName, updateReq.getFloorName())
                .ne(SmsDormitoryFloor::getId, updateReq.getId()));
        if (!dormitoryFloorList.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_NAME_EXIST);
        }

        smsDormitoryFloor.setFloorName(updateReq.getFloorName());
        dormitoryFloorMapper.updateById(smsDormitoryFloor);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getDormitoryFloorList(Integer pageNum, Integer pageSize, String name, String buildingId) {
        Page<SmsDormitoryFloor> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<SmsDormitoryFloor> dormitoryFloorLambdaQueryWrapper = new LambdaQueryWrapper<SmsDormitoryFloor>()
                .orderByAsc(SmsDormitoryFloor::getFloorName);
        if (!isNullOrEmpty(name)) {
            dormitoryFloorLambdaQueryWrapper.like(SmsDormitoryFloor::getFloorName,name);
        }
        if (!isNullOrEmpty(buildingId)) {
            dormitoryFloorLambdaQueryWrapper.eq(SmsDormitoryFloor::getBuildingId,buildingId);
        }
        dormitoryFloorMapper.selectPage(page,dormitoryFloorLambdaQueryWrapper);
        List<SmsDormitoryFloorResp> dormitoryFloorList = page.getRecords()
                .stream()
                .map(smsDormitoryFloor -> {
                    SmsDormitoryFloorResp smsDormitoryFloorResp = new SmsDormitoryFloorResp();
                    BeanUtils.copyProperties(smsDormitoryFloor,smsDormitoryFloorResp);
                    SmsDormitoryBuilding smsDormitoryBuilding = dormitoryBuildingMapper.selectById(smsDormitoryFloor.getBuildingId());
                    if (!isNullOrEmpty(smsDormitoryBuilding)) {
                        smsDormitoryFloorResp.setBuildingName(smsDormitoryBuilding.getBuildingName());
                    }
                    List<SmsDormitory> houseNumberList = dormitoryMapper.selectList(new LambdaQueryWrapper<SmsDormitory>()
                            .eq(SmsDormitory::getFloorId, smsDormitoryFloor.getId()));
                    if (houseNumberList.isEmpty()) {
                        smsDormitoryFloorResp.setFlag(0);//没有设置房间
                    }else {
                        smsDormitoryFloorResp.setFlag(1);
                    }
                    return smsDormitoryFloorResp;
                })
                .collect(Collectors.toList());
        int total = (int) page.getTotal();
        return CommonResult.success(dormitoryFloorList,total);
    }
}
